package com.breaktian.share;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Utils {
    static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
    }

    public static byte[] compressImage(String filePath, int maxSize) {
        if(TextUtils.isEmpty(filePath)){
            return null;
        }
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int quality = 100;

        //PNG格式压缩忽略quality参数 所以必须以JPEG格式压缩
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
        while (bos.toByteArray().length > maxSize) {
            quality -= 20;
            bos.reset();
            if (quality <= 0) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 0, bos);
                break;
            }
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
        }
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
            System.gc();
        }
        return bos.toByteArray();
    }
}
